package tree.huffman;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-06-05 14:56
 * @ Description : 哈夫曼树: WPL(带权路径长度)最小的树
 */
public class HuffmanTree
{
    public static void main(String[] args)
    {
        int[] array = {13, 7, 8, 3, 29, 6, 1};
        preOrder(create(array));
    }

    /**
     * @param root: 根节点
     * @return void
     * @Description 前序遍历
     **/
    public static void preOrder(Node root)
    {
        if (root != null)
        {
            root.preOrder();
        }
        else
        {
            System.out.println("根节点为空");
        }
    }

    /**
     * @param array: 权值数组
     * @return Node: 生成树的根节点
     * @Description 生成Huffman树
     **/
    public static Node create(int[] array)
    {
        //初始化: 对array提供的权值数组构建相应的节点，放入List中方便操作
        List<Node> nodes = new ArrayList<>();
        for (int i : array)
        {
            nodes.add(new Node(i));
        }

        //处理
        while (nodes.size() > 1)
        {
            //1. 节点排序(升序)
            Collections.sort(nodes);

            //2. 取出权值最小的两个节点
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);

            //3. 构成新的二叉树
            Node parent = new Node(leftNode.weight + rightNode.weight);
            parent.left = leftNode;
            parent.right = rightNode;

            //4. 从nodes中删除处理过的两个节点,加入新的节点
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }

        //返回根节点
        return nodes.get(0);
    }

}

//节点类
class Node implements Comparable<Node>
{
    public int weight;
    public char info;
    public Node left;
    public Node right;

    public Node(int weight)
    {
        this.weight = weight;
    }

    @Override
    public String toString()
    {
        return "Node{" +
                "weight=" + weight +
                '}';
    }

    @Override
    public int compareTo(Node o)
    {
        //升序
        return this.weight - o.weight;
    }

    //前序遍历
    public void preOrder()
    {
        System.out.println(this);
        if (this.left != null)
        {
            this.left.preOrder();
        }
        if (this.right != null)
        {
            this.right.preOrder();
        }
    }
}
